﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CliffPusher
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (!System.Diagnostics.Debugger.IsAttached)
            {
                AppDomain currentDomain = AppDomain.CurrentDomain;
                currentDomain.UnhandledException += CurrentDomain_UnhandledException;

                Application.ThreadException += Application_ThreadException;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            HandleException(e.Exception, "Application");
            Application.Exit();
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException(e.ExceptionObject as Exception, "AppDomain");
        }

        private static void HandleException(Exception ex, string name)
        {
            try
            {
                var msg = GetDetails(ex);
                MessageBox.Show(msg, $"Unhandled Exception ({name})");
            }
            catch(Exception)
            {
                MessageBox.Show("Unhandled exception in exception handler!");
            }
        }
        
        private static string GetDetails(Exception ex)
        {
            return ex.Message + Environment.NewLine
                 + Environment.NewLine
                 + ex.StackTrace
                 + Environment.NewLine
                 + (ex.InnerException != null ? Environment.NewLine + GetDetails(ex.InnerException) : "");
        }
    }
}
